package com.knowledgegraph.controller;

import com.knowledgegraph.entity.Node;
import com.knowledgegraph.entity.NodeRelation;
import com.knowledgegraph.service.G6DataConversionService;
import com.knowledgegraph.service.GraphService;
import com.knowledgegraph.service.KnowledgeGraphService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/knowledge-graph")
@Tag(name = "Knowledge Graph API", description = "知识图谱节点管理接口")
public class NodeController {
    
    @Autowired
    private KnowledgeGraphService knowledgeGraphService;
    
    @Autowired
    private G6DataConversionService g6DataConversionService;
    
    @Autowired
    private GraphService graphService;
    
    @PostMapping("/nodes")
    @Operation(summary = "创建节点", description = "创建新的知识图谱节点")
    public ResponseEntity<Node> createNode(@Valid @RequestBody Node node) {
        Node createdNode = knowledgeGraphService.createNode(node);
        return ResponseEntity.ok(createdNode);
    }
    
    @GetMapping("/nodes/{id}")
    @Operation(summary = "获取节点详情", description = "根据ID获取节点详细信息")
    public ResponseEntity<Node> getNode(@Parameter(description = "节点ID") @PathVariable Long id) {
        Optional<Node> node = knowledgeGraphService.getNodeById(id);
        return node.map(ResponseEntity::ok)
                  .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/nodes")
    @Operation(summary = "获取所有节点", description = "获取所有知识图谱节点列表")
    public ResponseEntity<List<Node>> getAllNodes(
            @Parameter(description = "节点类型过滤") @RequestParam(required = false) String nodeType,
            @Parameter(description = "名称搜索") @RequestParam(required = false) String name) {
        
        List<Node> nodes;
        if (nodeType != null && !nodeType.isEmpty()) {
            nodes = knowledgeGraphService.getNodesByType(nodeType);
        } else if (name != null && !name.isEmpty()) {
            nodes = knowledgeGraphService.searchNodesByName(name);
        } else {
            nodes = knowledgeGraphService.getAllNodes();
        }
        
        return ResponseEntity.ok(nodes);
    }
    
    @PutMapping("/nodes/{id}")
    @Operation(summary = "更新节点", description = "更新现有节点信息")
    public ResponseEntity<Node> updateNode(
            @Parameter(description = "节点ID") @PathVariable Long id,
            @Valid @RequestBody Node node) {
        
        if (!knowledgeGraphService.getNodeById(id).isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        node.setId(id);
        Node updatedNode = knowledgeGraphService.updateNode(node);
        return ResponseEntity.ok(updatedNode);
    }
    
    @DeleteMapping("/nodes/{id}")
    @Operation(summary = "删除节点", description = "删除指定节点")
    public ResponseEntity<Void> deleteNode(@Parameter(description = "节点ID") @PathVariable Long id) {
        if (!knowledgeGraphService.getNodeById(id).isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        knowledgeGraphService.deleteNode(id);
        return ResponseEntity.noContent().build();
    }
    
    @PostMapping("/relations")
    @Operation(summary = "创建节点关系", description = "在两个节点之间创建关系")
    public ResponseEntity<NodeRelation> createRelation(@Valid @RequestBody NodeRelation relation) {
        NodeRelation createdRelation = knowledgeGraphService.createNodeRelation(relation);
        return ResponseEntity.ok(createdRelation);
    }
    
    @GetMapping("/nodes/{id}/relations")
    @Operation(summary = "获取节点关系", description = "获取指定节点的所有关系")
    public ResponseEntity<List<NodeRelation>> getNodeRelations(
            @Parameter(description = "节点ID") @PathVariable Long id,
            @Parameter(description = "关系方向：incoming, outgoing, all") @RequestParam(defaultValue = "all") String direction) {
        
        List<NodeRelation> relations;
        switch (direction.toLowerCase()) {
            case "incoming":
                relations = knowledgeGraphService.getRelationsByTargetNode(id);
                break;
            case "outgoing":
                relations = knowledgeGraphService.getRelationsBySourceNode(id);
                break;
            default:
                relations = knowledgeGraphService.getAllRelationsForNode(id);
                break;
        }
        
        return ResponseEntity.ok(relations);
    }
    
    @DeleteMapping("/relations/{id}")
    @Operation(summary = "删除关系", description = "删除指定的节点关系")
    public ResponseEntity<Void> deleteRelation(@Parameter(description = "关系ID") @PathVariable Long id) {
        knowledgeGraphService.deleteNodeRelation(id);
        return ResponseEntity.noContent().build();
    }
}